package polygon.cli;

import org.apache.commons.cli.*;

/**
 * @author MikeMirzayanov (mirzayanovmr@gmail.com)
 */
public abstract class Command {
    private Cli cli;

    private String[] args;
    private Options options = new Options();
    private CommandLine commandLine;

    public abstract String getDescription();

    public void setCli(Cli cli) {
        this.cli = cli;
    }

    public void setArgs(String[] args) {
        this.args = args;
    }

    public Cli getCli() {
        return cli;
    }

    public String[] getArgs() {
        return args;
    }

    public Options getOptions() {
        return options;
    }

    public CommandLine getCommandLine() {
        return commandLine;
    }

    public void init() {
        setupOptions();
        
        CommandLineParser parser = new GnuParser();

        try {
            commandLine = parser.parse(options, args, true);
            if (args.length > 0 && args[args.length - 1].equalsIgnoreCase("--help")) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("Command " + getClass().getSimpleName() + ":", getOptions());
                System.exit(1);
            }
        } catch (ParseException e) {
            throw new CommandException("Can't parse command line: " + e.getMessage(), e);
        }
    }

    public abstract void setupOptions();
    public abstract void run();
}
